import pymysql
import threading

lock = threading.Lock()


class DB():
    def __init__(self):
        self.conn = pymysql.connect(host='localhost', port=3306, user='root', password='123', db='financial',
                                    charset='utf8', cursorclass=pymysql.cursors.DictCursor)
        self.cursors = self.conn.cursor()

    def update(self, sql):
        lock.acquire()
        self.cursors.execute(sql)
        lock.release()
        self.conn.commit()
        return self.cursors.lastrowid

    def find(self, sql):
        lock.acquire()
        self.cursors.execute(sql)
        lock.release()
        data = self.cursors.fetchone()
        return data

    def find_all(self, sql):
        lock.acquire()
        self.cursors.execute(sql)
        lock.release()
        data = self.cursors.fetchall()
        self.conn.commit()
        return data

    # 删除方法
    def delete(self, sql):
        # 创建游标对象
        self.cursor = self.conn.cursor()
        # 执行sql语句
        self.cursor.execute(sql)
        # 提交sqlself.conn.commit()
        self.conn.commit()

        return "delete ok"

    # 插入方法
    def insert(self, sql):
        # 创建游标对象
        self.cursor = self.conn.cursor()
        # 执行sql语句
        self.cursor.execute(sql)
        # 提交sql
        self.conn.commit()

    # 查询方法 单个数据
    def get_one(self, sql):
        self.cursor = self.conn.cursor()
        # 执行sql语句
        self.cursor.execute(sql)
        # 提交sql
        res = self.cursor.fetchone()
        self.conn.commit()
        # 返回结果集
        return res

    # 查询方法 多个数据
    def get_all(self, sql):
        self.cursor = self.conn.cursor()
        # 执行sql语句
        self.cursor.execute(sql)
        # 提交sql
        res = self.cursor.fetchall()
        self.conn.commit()
        # 返回结果集
        return res

    def close(self):
        self.cursors.close()
        self.conn.close()


db1 = DB()
